<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ResetCarbarn;
use App\Models\Carbarn;
use App\Http\Controllers\Controller;
use App\Models\Station;
use App\Models\Order;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use GuzzleHttp\Client;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class CarbarnController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('洗车舱')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('洗车舱')
            ->description('编辑')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('洗车舱')
            ->description('创建')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Carbarn);

        $grid->model()->with(['station']);

        $grid->id('Id');
        $grid->name('名称');
        $grid->code('编码');
        $grid->boxId('盒子ID号');
        $grid->address('详细地址');
        $grid->shortAddr('简略地址');
        $grid->longitude('经度');
        $grid->latitude('纬度');
        $grid->mcstationId('投放门店')->display(function () {
            return $this->station ? $this->station->name : "";
        });
        $grid->addTime('添加时间')->display(function ($item) {
            $addTimeOriginal = $this->getOriginal('addTime');
            if ($addTimeOriginal) {
                return $this->addTime->toDateTimeString();
            }
            return '';
        });

        $grid->filter(function ($filters) {
            $filters->equal('mcstationId', '门店')->select(Station::pluck('name', 'id'));
        });

        $grid->disableExport();
        $grid->actions(function ($actions) {
            $actions->disableView();
//            $actions->append(new ResetCarbarn($actions->getKey()));
            $actions->append(sprintf('<a href="%s" target="_blank" style="padding-left: 10px;">小程序二维码</a>', route('carbarn.qrcode.weixin', ['cartCode' => $actions->getKey()])));
            $actions->append(sprintf('<a href="%s" target="_blank" style="padding-left: 10px;">App二维码</a>', route('carbarn.qrcode.app', ['cartCode' => $actions->getKey()])));
        });


        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Carbarn::findOrFail($id));

        $show->id('Id');
        $show->name('Name');
        $show->code('Code');
        $show->addTime('AddTime');
        $show->address('Address');
        $show->shortAddr('ShortAddr');
        $show->longitude('Longitude');
        $show->latitude('Latitude');
        $show->mcstationId('McstationId');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Carbarn);

        $form->text('name', '名称')->rules(['required']);
        $form->text('code', '编码')->rules(['required']);
        $form->text('boxId', '盒子ID号')->rules(['required', 'integer']);
        $form->text('address', '详细地址')->rules(['required']);
        $form->text('shortAddr', '简略地址')->rules(['required']);
        $form->text('longitude', '经度')->rules(['required']);
        $form->text('latitude', '纬度')->rules(['required']);
        $form->text('tipInfo', '小提示');
        $form->textarea('softTips', '温馨提示');
        $form->image('coverPath', '封面图')->rules('required')->uniqueName();
        $form->image('navigateImg', '导航图')->rules('required')->uniqueName();
        $form->distpicker(['provinceCode', 'cityCode', 'districtCode'], '位置区域')->attribute('data-value-type', 'code');
        $form->radio('mcstationId', '投放门店')->options(Station::pluck('name', 'id'));

        return $form;
    }

    public function topToday()
    {
        $topCarbarn = Order::where("carbarnId", ">", 0)
            ->where("addTime", ">=", strtotime('today'))
            ->orderByRaw("count(carbarnId) desc")->groupBy("carbarnId")->selectRaw("carbarnId, count(carbarnId) as counts")->get();

        $topCarbarnOrderCounts = $topCarbarn->pluck('counts', 'carbarnId');

        $carbarnList = Carbarn::with(['station'])->whereIn("id", $topCarbarn->pluck("carbarnId")->all())
            ->get()->each(function (&$item) use ($topCarbarnOrderCounts) {
                $item->order_counts = $topCarbarnOrderCounts->get($item->id);
                $item->name_formatted = sprintf("%s(%s)", $item->name, $item->station->name);
            });

        return response()->json($carbarnList->toArray());
    }

    public function qrcodeWeixin()
    {
        $id = request('cartCode');
        $carbarn = Carbarn::findOrFail($id);
//        $miniApp = \EasyWeChat::miniProgram();
//        $scene = sprintf("cbno=%s", $carbarn->code);
//        $options = [
//            'page' => 'pages/order/order',
//        ];
//        $page = sprintf('pages/order/order?cartCode=%s', $carbarn->code);
        $url = "http://www.abt2017.com/qrc?cartCode=" . $carbarn->code;
        logger(sprintf("%s, url: %s", __METHOD__, $url));
//        $response = $miniApp->app_code->getQrCode($page);
//        $contents = $response->getBody()->getContents();
        $contents = QrCode::format('png')->size(500)->generate($url);
        if (strlen($contents) < 100)
        {
            //认为是错误
            return $contents;
        }
        return response()->streamDownload(function () use ($contents) {
            echo $contents;
        }, sprintf("weixin_carbarn_%s_%s_%s.png", $carbarn->id, $carbarn->code, date('Ymd_His')));

    }

    public function qrcodeApp()
    {
        $id = request('cartCode');
        $carbarn = Carbarn::findOrFail($id);
        $page = sprintf('pages/order/order?cartCode=%s', $carbarn->code);
        logger(sprintf("%s, page: %s", __METHOD__, $page));
        $contents = QrCode::format('png')->size(500)->generate($page);
        if (strlen($contents) < 100)
        {
            //认为是错误
            return $contents;
        }
        return response()->streamDownload(function () use ($contents) {
            echo $contents;
        }, sprintf("app_carbarn_%s_%s_%s.png", $carbarn->id, $carbarn->code, date('Ymd_His')));

    }

    public function reset()
    {
        $carbarn = Carbarn::findOrFail(request('id'));
        $http = new Client();
        $config = config('meiche');
        //先获取token
        $url = sprintf('%s/core/connect/token', $config['box_id_server']);
        $response = $http->post($url, [
            'form_params' => [
                "username" => $config['box_username'],
                "password" => $config['box_password'],
                "client_id" => $config['box_dev_id'],
                "client_secret" => $config['box_dev_secret'],
                "scope"=>'openid offline_access fbox email profile',
                "grant_type"=>'password',
            ]
        ]);
        if (($statusCode = $response->getStatusCode()) != 200) {
            return api("获取 token http 状态码($statusCode)错误");
        }
        $body = (string)$response->getBody();
        $bodyData = json_decode($body, true);
        if (empty($bodyData['access_token'])) {
            return api("获取 token 返回值错误：$body");
        }
        $accessToken = $bodyData['access_token'];
        \Log::info(__METHOD__, [$carbarn->code, $accessToken]);
        unset($response);

        //进行复位请求
        $url = sprintf('%s/v2/dmon/value?boxNo=%s', $config['box_api_base_url'], $carbarn->code);
        try {
            $response = $http->post($url, [
                'headers' => [
                    'Authorization' => "Bearer $accessToken",
                ],
                'json' => [
                    'name' => '复位',
                    'type' => 0,
                    'value' => 1,
                ],
            ]);
        } catch (\Exception $e) {
            $errorMsg = $e->getMessage();
            if ($e->hasResponse()) {
                $fBoxCode = $e->getResponse()->getHeader('X-FBox-Code');
                if ($fBoxCode) {
                    $errorMsg .= ", X-FBox-Code: {$fBoxCode[0]}";
                }
            }

            return api($errorMsg);
        }

        if (($statusCode = $response->getStatusCode()) != 200) {
            return api("复位操作 http 状态码($statusCode)错误");
        }

        return api(RET_OK, '操作成功', ['response' => (string)$response->getBody()]);

    }
}
